package com.daydr3am.thenation;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import org.w3c.dom.Node;

import com.coe3.data.AllIntent;
import com.coe3.data.Information;
import com.daydr3am.lib.ImageLoader;
import com.daydr3am.lib.TouchyWebView;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.Html;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class Material extends LinearLayout {
	public Node obj;
	int fontSize;
	int count_clickfont=0;
	WebView web;
	
	private Context context;
	
	OnClickListener back=new OnClickListener() {
		@Override
		public void onClick(View v)  {
			TheNationMain main=(TheNationMain) v.getContext();
			main.backToHome();
		}
	};
	
	OnClickListener upfont = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			
			if(v.getId()==R.id.material_upfont)
			{
				count_clickfont += 1;
				 
				Log.d("thenation", "font size origin:"+web.getSettings().getDefaultFontSize());
				
				if(count_clickfont < 3){
					
					fontSize += 2;
					web.getSettings().setDefaultFontSize(fontSize);
				}else{
					count_clickfont = 0;
					//fontSize = web.getSettings().getDefaultFontSize();
					fontSize = 16;
					web.getSettings().setDefaultFontSize(fontSize);
				}
			}
			
			if(v.getId()==R.id.btn_Share)
			{
				
				Log.e("TNT","btn_Share");

				Intent sendIntent = new Intent();
				sendIntent.setAction(Intent.ACTION_SEND);
				sendIntent.putExtra(Intent.EXTRA_TITLE,Stitle);
				sendIntent.putExtra(Intent.EXTRA_SUBJECT,"");
				sendIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON,R.drawable.back_button);
				
				sendIntent.putExtra(Intent.EXTRA_TEXT,Html.fromHtml(detail)+"\n"+Html.fromHtml(description)+"\n http://www.nationmultimedia.com/national/Anti-cheating-hats-will-not-be-used-again-universi-30212839.html");
				sendIntent.setType("text/plain");
				context.startActivity(sendIntent);
				
			}
				
			
		}
	};

	public Material(Context context, AttributeSet attrs) {
		super(context, attrs); 
		
		this.context=context;
		setOnTouchListener(new OnTouchListener() { 
			
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				return true;
			}
		});
	}
	@Override
	protected void onFinishInflate() {
		if(findViewById(R.id.material_back)!=null) 
			findViewById(R.id.material_back).setOnClickListener(back);

	    super.onFinishInflate();    
	}
	

	
	private String detail,description,Stitle;
	
	@SuppressLint("SetJavaScriptEnabled")
	public void setObj(Node newObj){
		obj=newObj;
		TextView  column=(TextView) findViewById(R.id.material_column);
		TextView  label=(TextView) findViewById(R.id.material_label);
		TextView  title=(TextView) findViewById(R.id.material_title); 
		TextView  by=(TextView) findViewById(R.id.material_by);
		HorizontalScrollView  scroll=(HorizontalScrollView) findViewById(R.id.material_scroll);
		ImageView  fullImage=(ImageView) findViewById(R.id.material_fullimage);
		web=(WebView) findViewById(R.id.material_web);
		TextView descriptionText= (TextView) findViewById(R.id.material_description);
		ImageView material_upfont = (ImageView)findViewById(R.id.material_upfont);
		material_upfont.setOnClickListener(upfont);
		
		
		ImageView btn_Share= (ImageView)findViewById(R.id.btn_Share);
		btn_Share.setOnClickListener(upfont);
		
		fontSize = web.getSettings().getDefaultFontSize();
		
		detail=obj.getChildNodes().item(11).getTextContent();
		description=obj.getChildNodes().item(9).getTextContent();
		Stitle=obj.getChildNodes().item(5).getTextContent().toString();
		
		
		
		column.setText(obj.getChildNodes().item(1).getTextContent());
		label.setText(obj.getChildNodes().item(3).getTextContent());
		title.setText(obj.getChildNodes().item(5).getTextContent());
		by.setText(obj.getChildNodes().item(7).getTextContent());
		scroll.scrollTo(0, 0);

		//xxx
//		ImageLoader imgLoader = new ImageLoader(getContext());  
//		imgLoader.DisplayImage(obj.getChildNodes().item(19).getChildNodes().item(0).getTextContent(), 0, fullImage);
		
		if(TheNationMain.getIsOffline(getContext())){
			File path = new File(TheNationMain.getPathCurrentNew(getContext()), obj.getChildNodes().item(19).getChildNodes().item(0).getTextContent());
			Bitmap mBitmap = null;
			mBitmap = BitmapFactory.decodeFile(path.getAbsolutePath());
			fullImage.setImageBitmap(mBitmap);
		} else {
			if(Information.isOnline(getContext())){
				ImageLoader imgLoader = new ImageLoader(getContext());  
				imgLoader.DisplayImage(obj.getChildNodes().item(19).getChildNodes().item(0).getTextContent(), 0, fullImage);
	    		Information.logDEBUG("img url: " + obj.getChildNodes().item(19).getChildNodes().item(0).getTextContent());
			}//end if
		}//end if
		
		web.setWebViewClient(new WebViewClient() );
	    web.getSettings().setJavaScriptEnabled(true);
//	    web.setInitialScale(1);

    	Log.v("hello", getHtmlCode(detail, description));
        if(getResources().getConfiguration().orientation==Configuration.ORIENTATION_LANDSCAPE){
    		web.loadData(getHtmlCode(detail, description), "text/html; charset=UTF-8", null);
    		web.loadData(getHtmlCode(detail, description), "text/html; charset=UTF-8", null);
        }
        else if(getResources().getConfiguration().orientation==Configuration.ORIENTATION_PORTRAIT){
    		web.loadData(getHtmlCode(detail, ""), "text/html; charset=UTF-8", null);
    		web.loadData(getHtmlCode(detail, ""), "text/html; charset=UTF-8", null);
        }
        Log.v("hello", "pass func");
		if(descriptionText!=null)
			descriptionText.setText(description);
		
		Information.logDEBUG("<============================ InitSlide Ads =================>");
		
		TouchyWebView web=(TouchyWebView) findViewById(R.id.material_ad);
		
		int index = TheNationMain.getPageIndex(getContext());
		
		if(TheNationMain.getIsOffline(getContext())){
			String url = "file://" + TheNationMain.getPathCurrentNew(getContext());
			web.url = url + "/Section-Page.html";
		} else {
			if(Information.isOnline(getContext())) {
				int section=TheNationMain.getSectionFromPage(index, getContext())+1;
				web.url="http://www.nationmultimedia.com/new/rss/ipad_v2/banner/NT_Sidebannen"+section+".htm";
			}//end if
		}//end if
		
		web.onShowView();
    	web.getSettings().setDefaultZoom(WebSettings.ZoomDensity.MEDIUM);
	}
	
	public String getHtmlCode(String detail,String description){
		try {
            InputStream is = getContext().getAssets().open("test_css.txt");
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            String text = new String(buffer);
            
//            NSMutableString *headWeb=[[NSMutableString alloc] initWithCapacity:0];
//        	[headWeb appendString:textHeader];
            text+=description;
            text+="</p><span id=\"p_text\"><br>";
            text+=detail;
        	
//        	if([[NSUserDefaults standardUserDefaults] integerForKey:[self getThisMonth]]>LimitNewsUnregis
//        	   &&[[[NSUserDefaults standardUserDefaults] stringForKey:@"expire"] isEqualToString:@"0"]){
//        		[headWeb appendString:@"<br><br><img src=\"Line.png\" ><br><br><p>"];
//        		[headWeb appendString:@"Subscribe now for unlimited access to The Nation"];
//        		[headWeb appendString:@"<br/><a style=\"text-decoration:none;\" href=\"https://signin.nationmultimedia.com/service/\">SUBSCRIBE NOW/RENEWMEMBER SHIP</a> <br/>"];
//        		[headWeb appendString:@"Already a Digital Subscriber?"];
//        		[headWeb appendString:@"<br/><a style=\"text-decoration:none;\" href=\"https://signin.nationmultimedia.com/service/login.php/\">SIGN IN</a> <br/>"];
//        		[headWeb appendString:@"Existing Print Subscriber"];
//        		[headWeb appendString:@"<br/><a style=\"text-decoration:none;\" href=\"https://signin.nationmultimedia.com/service/login-newspaper.php/\">GET FREE ACCESS</a> <br/>"];
//        		[headWeb appendString:@"</p>"];
//        	}
//        	[headWeb appendString:@"</span>"];
        	
            text+="</body> </html>";
            
            
            if(getResources().getConfiguration().orientation==Configuration.ORIENTATION_LANDSCAPE){
                text=text.replace("ContentHeight", "540");
            }
            else if(getResources().getConfiguration().orientation==Configuration.ORIENTATION_PORTRAIT){
                text=text.replace("ContentHeight", "1000");
            }
            text=text.replace("ColumnWidth", "310");
            text=text.replace("FontNow", "14");
            text=text.replace("FontBigger", "16");
//        	if([adPath length]>0){
//        		headWeb =[[NSMutableString alloc] initWithString:[headWeb stringByReplacingOccurrencesOfString:
//        														  @"http://www.nationmultimedia.com/new/rss/ipad_v2/banner/NT_Insidenews.htm" withString:adPath] ];
//        	}
//        	NSString *imagePath = [[NSBundle mainBundle] resourcePath];
//        	imagePath = [imagePath stringByReplacingOccurrencesOfString:@"/" withString:@"//"];
//        	imagePath = [imagePath stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
            return text;

            
            
            // Finally stick the string into the text view.
        } catch (IOException e) {
            // Should never happen!
            throw new RuntimeException(e);
        }
	}
}
